<?php
class Dp_Model_Mapper
{
	protected $_dbTable;

	protected static $_mapperName;
	protected static $_modelName;
	protected static $_dbTableName;

	public function __construct($name)
	{
		static::init($name);
	}

	protected static function init($name)
	{		
		static::$_mapperName = $name;
		static::$_modelName = str_replace('Mapper_', '', static::$_mapperName);
		static::$_dbTableName = str_replace('Mapper_', 'DbTable_', static::$_mapperName);
	}

	protected function mapperToModel($row, $model)
	{
		foreach ($model->properties as $property)
		{
			$funcName = 'set' . ucfirst($property);
			$model->$funcName($row->property);
		}
	}

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) 
		{
			$dbTable = new $dbTable();
		}

		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception("$dbTable is invalid table data gateway provided");
		}

		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) 
		{
			$this->setDbTable(static::$_dbTableName);
		}
		return $this->_dbTable;
	}

	public function save(Dp_Model $model)
	{		
		$data = array();

		foreach ($model->properties as $property)
		{
			$funcName = 'get' . ucfirst($property);
			$data[$property] = $model->$funcName();
		}		

		if (null === ($id = $model->getId())) 
		{
			unset($data['id']);
			$this->getDbTable()->insert($data);
		}
		else 
		{
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}

	public function find($id, Dp_Model$model)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) 
		{
			return;
		}

		$row = $result->current();
		$this->mapperToMoel($row, $model);
	}

	public function fetchAll($where = null, $order = null, $count = null, $offset = null)
	{
		$resultSet = $this->getDbTable()->fetchAll($where, $order, $count, $offset);
		$entries   = array();
		foreach ($resultSet as $row) 
		{
			$entry = new $model_name;
			$this->mapperToMoel($row, $entry);
			$entry->setMapper($this);
			$entries[] = $entry;
		}
		return $entries;
	}
}
